import { createStore } from 'vuex'
import request from '@/utils/request'
import { sanitizeObjectKeys } from '@/utils'

export default createStore({
  state: {
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null,
    isAuthenticated: !!localStorage.getItem('token')
  },
  mutations: {
    setUser(state, user) {
      const sanitizedUser = sanitizeObjectKeys(user)
      state.user = sanitizedUser
      state.isAuthenticated = !!sanitizedUser
      if (sanitizedUser) {
        localStorage.setItem('user', JSON.stringify(sanitizedUser))
      } else {
        localStorage.removeItem('user')
      }
    },
    setToken(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
        state.isAuthenticated = true
      } else {
        localStorage.removeItem('token')
        state.isAuthenticated = false
      }
    },
    logout(state) {
      state.user = null
      state.token = null
      state.isAuthenticated = false
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('userName')
    }
  },
  actions: {
    async login({ commit }, credentials) {
      try {
        console.log('发起登录请求，凭据:', credentials)
        
        const response = await request({
          url: '/api/auth/token',
          method: 'post',
          data: credentials
        })
        
        console.log('登录响应:', response)
        
        if (!response || !response.access_token) {
          console.error('登录响应缺少令牌信息:', response)
          throw new Error('登录响应缺少令牌信息');
        }
        
        commit('setToken', response.access_token)
        
        // 保存用户名到本地存储，便于其他组件使用
        if (credentials.username) {
          localStorage.setItem('userName', credentials.username);
        }
        
        // 确保用户数据对象不包含数字键
        const userData = sanitizeObjectKeys({
          username: credentials.username,
          lastLogin: new Date().toISOString()
        })
        commit('setUser', userData)
        
        return true
      } catch (error) {
        console.error('Login error:', error)
        // 确保错误可以被正常序列化和处理
        if (error instanceof Error) {
          throw new Error(error.message || '登录失败');
        }
        throw error
      }
    },
    logout({ commit }) {
      commit('logout')
    },
    checkAuth({ state, commit }) {
      const token = localStorage.getItem('token')
      const userJson = localStorage.getItem('user')
      
      if (token && userJson) {
        commit('setToken', token)
        try {
          const userData = sanitizeObjectKeys(JSON.parse(userJson))
          commit('setUser', userData)
        } catch (e) {
          console.error('Failed to parse user data:', e)
          commit('logout')
        }
      } else {
        commit('logout')
      }
      
      return state.isAuthenticated
    }
  },
  getters: {
    isAuthenticated: state => state.isAuthenticated,
    user: state => state.user,
    token: state => state.token
  }
}) 